package com.jt.controller;

import com.jt.annotation.RequiredLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/resource/")
public class ResController {
    @Value("${jt.resource.path}")
    private String resourcePath;
    @Value("${jt.resource.host}")
    private String resourceHost;

    @PreAuthorize("hasAuthority('sys:res:create')")
    @RequiredLog("文件上传")
    @PostMapping("/upload/")
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        //创建存储目录
        String dateDir = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //构建目录文件对象
        File uploadFileDir = new File(resourcePath, dateDir);
        if(!uploadFileDir.exists()){
            uploadFileDir.mkdirs();
        }
        //给文件取名
        String originalFilename = uploadFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构建新的文件名
        String newFilePrefix = UUID.randomUUID().toString();
        String newFileName = newFilePrefix+ext;
        //实现文件上传
        File file = new File(uploadFileDir,newFileName);
        //上传文件
        uploadFile.transferTo(file);
        String fileRealPath = resourceHost+dateDir+"/"+newFileName;
        log.debug("fileRealPath {}", fileRealPath);
        return fileRealPath;
    }
}
